<template>
  <div class="app-container">
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 退税申报标签页 -->
      <el-tab-pane label="退税申报" name="declaration">
        <el-card>
          <div slot="header" class="clearfix">
            <span>退税申报</span>
          </div>
          
          <!-- 数据准备区 -->
          <el-card class="box-card" style="margin-bottom: 20px;">
            <div slot="header" class="clearfix">
              <span>数据准备区</span>
              <el-button
                style="float: right; margin-left: 10px;"
                type="primary"
                size="mini"
                icon="el-icon-refresh"
                @click="refreshPendingList"
                v-hasPermi="['fiscale:refund:declaration:refresh']"
              >刷新</el-button>
            </div>
            
            <!-- 操作按钮 -->
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-document"
                  size="mini"
                  :disabled="pendingSelection.length === 0"
                  @click="handleGenerateData"
                  v-hasPermi="['fiscale:refund:declaration:generate']"
                >生成退税数据</el-button>
              </el-col>
            </el-row>
            
            <!-- 待申报列表 -->
            <el-table 
              v-loading="pendingLoading" 
              :data="pendingList" 
              @selection-change="handlePendingSelectionChange"
              ref="pendingTable"
            >
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="报关单号" align="center" prop="declarationNo" />
              <el-table-column label="发票号" align="center" prop="invoiceNo" />
              <el-table-column label="FOB金额" align="center" prop="fobAmount" />
              <el-table-column label="商品退税率" align="center" prop="taxRate" />
              <el-table-column label="应退税额" align="center" prop="refundAmount" />
              <el-table-column label="匹配时间" align="center" prop="matchingTime" width="180" />
            </el-table>
            
            <!-- 分页 -->
            <pagination
              v-show="pendingTotal > 0"
              :total="pendingTotal"
              :page.sync="pendingQueryParams.pageNum"
              :limit.sync="pendingQueryParams.pageSize"
              @pagination="getPendingList"
            />
          </el-card>
          
          <!-- 申报数据预览 -->
          <el-card class="box-card" v-if="showPreview">
            <div slot="header" class="clearfix">
              <span>申报数据预览</span>
              <el-button
                style="float: right;"
                type="primary"
                size="mini"
                icon="el-icon-upload"
                :disabled="!batchInfo"
                @click="handleSubmitDeclaration"
                v-hasPermi="['fiscale:refund:declaration:submit']"
              >正式申报</el-button>
            </div>
            
            <!-- 批次信息 -->
            <el-descriptions title="批次信息" :column="4" border>
              <el-descriptions-item label="批次号">{{ batchInfo.batchNo }}</el-descriptions-item>
              <el-descriptions-item label="总退税金额">{{ batchInfo.totalAmount }}</el-descriptions-item>
              <el-descriptions-item label="报关单数量">{{ batchInfo.declarationCount }}</el-descriptions-item>
              <el-descriptions-item label="状态">
                <el-tag v-if="batchInfo.status === 'pending'" type="info">待申报</el-tag>
                <el-tag v-else-if="batchInfo.status === 'submitting'" type="warning">申报中</el-tag>
                <el-tag v-else-if="batchInfo.status === 'processing'" type="primary">税务审核中</el-tag>
                <el-tag v-else-if="batchInfo.status === 'approved'" type="success">审批通过</el-tag>
                <el-tag v-else-if="batchInfo.status === 'refunding'" type="warning">退库处理中</el-tag>
                <el-tag v-else-if="batchInfo.status === 'completed'" type="success">退税款已到账</el-tag>
                <el-tag v-else-if="batchInfo.status === 'failed'" type="danger">申报失败</el-tag>
              </el-descriptions-item>
            </el-descriptions>
            
            <!-- 预览列表 -->
            <el-table v-loading="previewLoading" :data="previewList" style="margin-top: 20px;">
              <el-table-column label="报关单号" align="center" prop="declarationNo" />
              <el-table-column label="发票号" align="center" prop="invoiceNo" />
              <el-table-column label="FOB金额" align="center" prop="fobAmount" />
              <el-table-column label="商品退税率" align="center" prop="taxRate" />
              <el-table-column label="应退税额" align="center" prop="refundAmount" />
            </el-table>
          </el-card>
        </el-card>
      </el-tab-pane>
      
      <!-- 退税进度看板标签页 -->
      <el-tab-pane label="退税进度看板" name="progress">
        <el-card>
          <div slot="header" class="clearfix">
            <span>退税进度看板</span>
            <el-button
              style="float: right;"
              type="primary"
              size="mini"
              icon="el-icon-refresh"
              @click="refreshBatchList"
              v-hasPermi="['fiscale:refund:declaration:refresh']"
            >手动刷新</el-button>
          </div>
          
          <!-- 批次列表 -->
          <el-table v-loading="batchLoading" :data="batchList">
            <el-table-column label="批次号" align="center" prop="batchNo" />
            <el-table-column label="申报日期" align="center" prop="submitTime" width="180" />
            <el-table-column label="总退税金额" align="center" prop="totalAmount" />
            <el-table-column label="当前状态" align="center" prop="status">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 'pending'" type="info">待申报</el-tag>
                <el-tag v-else-if="scope.row.status === 'submitting'" type="warning">申报中</el-tag>
                <el-tag v-else-if="scope.row.status === 'processing'" type="primary">税务审核中</el-tag>
                <el-tag v-else-if="scope.row.status === 'approved'" type="success">审批通过</el-tag>
                <el-tag v-else-if="scope.row.status === 'refunding'" type="warning">退库处理中</el-tag>
                <el-tag v-else-if="scope.row.status === 'completed'" type="success">退税款已到账</el-tag>
                <el-tag v-else-if="scope.row.status === 'failed'" type="danger">申报失败</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="handleViewDetail(scope.row)"
                  v-hasPermi="['fiscale:refund:declaration:detail']"
                >查看详情</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-download"
                  @click="handleDownloadReceipt(scope.row)"
                  v-if="scope.row.status === 'approved' || scope.row.status === 'completed'"
                  v-hasPermi="['fiscale:refund:declaration:download']"
                >下载回执</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页 -->
          <pagination
            v-show="batchTotal > 0"
            :total="batchTotal"
            :page.sync="batchQueryParams.pageNum"
            :limit.sync="batchQueryParams.pageSize"
            @pagination="getBatchList"
          />
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 详情对话框 -->
    <el-dialog :title="detailTitle" :visible.sync="detailOpen" width="1200px" append-to-body>
      <el-table :data="detailList" style="margin-bottom: 20px;">
        <el-table-column label="报关单号" align="center" prop="declarationNo" />
        <el-table-column label="发票号" align="center" prop="invoiceNo" />
        <el-table-column label="FOB金额" align="center" prop="fobAmount" />
        <el-table-column label="商品退税率" align="center" prop="taxRate" />
        <el-table-column label="应退税额" align="center" prop="refundAmount" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPendingDeclaration, generateRefundData, submitRefundDeclaration, listBatches, getBatchDetail, refreshStatus, downloadReceipt } from "@/api/fiscale/refund";

export default {
  name: "RefundDeclaration",
  data() {
    return {
      // 活动标签页
      activeTab: "declaration",
      
      // 加载状态
      pendingLoading: true,
      previewLoading: false,
      batchLoading: false,
      
      // 待申报数据
      pendingList: [],
      pendingTotal: 0,
      pendingQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      pendingSelection: [],
      
      // 预览数据
      showPreview: false,
      batchInfo: null,
      previewList: [],
      
      // 批次数据
      batchList: [],
      batchTotal: 0,
      batchQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      
      // 详情对话框
      detailOpen: false,
      detailTitle: "",
      detailList: []
    };
  },
  created() {
    this.getPendingList();
  },
  methods: {
    /** 标签页切换 */
    handleTabClick(tab) {
      if (tab.name === "declaration") {
        this.getPendingList();
      } else if (tab.name === "progress") {
        this.getBatchList();
      }
    },
    
    /** 获取待申报列表 */
    getPendingList() {
      this.pendingLoading = true;
      listPendingDeclaration(this.pendingQueryParams).then(response => {
        this.pendingList = response.rows;
        this.pendingTotal = response.total;
        this.pendingLoading = false;
      }).catch(() => {
        // 如果API调用失败，使用模拟数据
        this.pendingList = [
          {
            matchingId: 1,
            declarationNo: "BG20250920001",
            invoiceNo: "FP20250920001",
            fobAmount: "10000.00",
            taxRate: "13%",
            refundAmount: "1300.00",
            matchingTime: "2025-09-20 10:00:00"
          }
        ];
        this.pendingTotal = 1;
        this.pendingLoading = false;
      });
    },
    
    /** 获取批次列表 */
    getBatchList() {
      this.batchLoading = true;
      listBatches(this.batchQueryParams).then(response => {
        this.batchList = response.rows;
        this.batchTotal = response.total;
        this.batchLoading = false;
      });
    },
    
    /** 刷新待申报列表 */
    refreshPendingList() {
      this.getPendingList();
      this.$message.success("刷新成功");
    },
    
    /** 刷新批次列表 */
    refreshBatchList() {
      this.getBatchList();
      this.$message.success("刷新成功");
    },
    
    /** 待申报多选 */
    handlePendingSelectionChange(selection) {
      this.pendingSelection = selection;
    },
    
    /** 生成退税数据 */
    handleGenerateData() {
      const matchingIds = this.pendingSelection.map(item => item.matchingId);
      if (matchingIds.length === 0) {
        this.$message.warning("请至少选择一条记录");
        return;
      }
      
      this.previewLoading = true;
      generateRefundData(matchingIds).then(response => {
        this.batchInfo = response.data;
        this.previewList = this.pendingSelection;
        this.showPreview = true;
        this.previewLoading = false;
        this.$message.success("生成退税数据成功");
      }).catch(() => {
        this.previewLoading = false;
      });
    },
    
    /** 正式申报 */
    handleSubmitDeclaration() {
      this.$confirm('确认提交申报吗？提交后将无法修改。', '确认申报', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return submitRefundDeclaration(this.batchInfo.batchId);
      }).then(() => {
        this.showPreview = false;
        this.batchInfo = null;
        this.previewList = [];
        this.getPendingList();
        this.getBatchList();
        this.$message.success("提交申报成功");
      }).catch(() => {});
    },
    
    /** 查看详情 */
    handleViewDetail(row) {
      getBatchDetail(row.batchId).then(response => {
        this.detailList = response.data.batchDetails || [];
        this.detailTitle = "批次详情 - " + row.batchNo;
        this.detailOpen = true;
      });
    },
    
    /** 下载回执 */
    handleDownloadReceipt(row) {
      downloadReceipt(row.batchId).then(response => {
        this.$message.success("回执文件下载链接生成成功");
        // 实际实现中应该触发文件下载
      });
    }
  }
};
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
</style>